﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System;
using LitJson;
using LuaFramework;

public class ViewEditor:EditorWindow
{
    [MenuItem("Tools/ViewEditor")]
    
    static void AddWindow()
    {
        //创建窗口
        Rect wr = new Rect(0, 0, 1024, 600);

        //另一种方式：
        //ViewEditor window = (ViewEditor)EditorWindow.GetWindow(typeof(ViewEditor), true, "ViewEditor");
        ViewEditor window = (ViewEditor)EditorWindow.GetWindowWithRect(typeof(ViewEditor), wr, true, "ViewEditor");
        window.Show();
    }

    public string[] layerTypeArr = new string[] { "NONE", "UNDERGROUND", "GROUND", "LOWSKY", "SKY", "HEAVEN", "SPACE", "MOON", "MARS","JUPITER", "PLUTO", "GALAXY_CENTER", "GEMINI", "BLACK_HOLE", "MASK", "TOP" };
    public string[] viewTypeArr = new string[] { "NONE",  "BACKGROUND", "PANEL", "DIALOG", "DIALOGA", "DIALOGB","DIALOGC","DIALOGD", "ALERT", "LOADING", "GUIDE", "MASK","MESSAGE","CUTSCENE"};
    public string[] constantTypeArr = new string[] { "false", "true" };
    public string[] hideSceneArr = new string[] { "false", "true" };
    public string[] hideAllVisibleArr = new string[] { "false", "true" };

    private List<Dictionary<string, string>> taskList = new List<Dictionary<string, string>>();
    private Vector2 scrollPos = Vector2.zero;
    private string reviewName;
    private bool init = false;

    // 版本目录
    public string projectDir = "";
    
    private void OnEnable()
    {
        projectDir = Application.dataPath + string.Format("/{0}/Lua", AppConst.AppName);

        LoadJsonFromFile();
    }

    void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        reviewName = EditorGUILayout.TextField("预操作viewName", reviewName, GUILayout.Width(400));
        if (GUILayout.Button("添加当前VIEW", GUILayout.Width(150)))
        {
            Dictionary<string, string> item = new Dictionary<string, string>();
            item.Add("viewName", reviewName);
            item.Add("layerType", "NONE");
            item.Add("viewType", "NONE");
            item.Add("hideScene", "FALSE");
            item.Add("hideAllVisible", "FALSE");
            item.Add("constantView", "FALSE");
            item.Add("viewPath", "");

            bool match = false;
            for (int i = 0; i < taskList.Count; i++)
            {
                Dictionary<string, string> t = taskList[i];
                string n;
                t.TryGetValue("viewName", out n);
                if (reviewName == n)
                {
                    match = true;
                    break;
                }
            }
            if (match == false)
            {
                taskList.Add(item);
                taskList.Sort((a, b) =>
                {
                    return a["viewName"].CompareTo(b["viewName"]);
                });
            }
        }
        EditorGUILayout.EndHorizontal();
        
        if (GUILayout.Button("保存并生成配置文件到目录", GUILayout.Width(300)))
        {
            SaveJsonToFile();

            string path = projectDir + "/Common/view_def.lua";
            string content = CreateLuaConfig(taskList, GetCodeModelContent("view_def_model"));
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir); 
            File.WriteAllText(path, content);

            //CreateFiles();
        }
        GUILayout.Space(30);

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("viewName", GUILayout.Width(100));
        EditorGUILayout.LabelField("layerType", GUILayout.Width(100));
        EditorGUILayout.LabelField("viewType", GUILayout.Width(100));
        EditorGUILayout.LabelField("hideScene", GUILayout.Width(100));
        EditorGUILayout.LabelField("hideAllVisible", GUILayout.Width(100));
        EditorGUILayout.LabelField("constantView", GUILayout.Width(100));
        EditorGUILayout.LabelField("viewPath", GUILayout.Width(100));
        EditorGUILayout.EndHorizontal();

        if (init)
        {
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
            for (int i = 0; i < taskList.Count; i++)
            {
                Dictionary<string, string> t = taskList[i];

                EditorGUILayout.BeginHorizontal();

                string viewName = t["viewName"];
                EditorGUILayout.LabelField(viewName, GUILayout.Width(100));

                string layerType = t["layerType"];
                int layerTypeIndex = Array.IndexOf(layerTypeArr, layerType);
                layerTypeIndex = EditorGUILayout.Popup(layerTypeIndex, layerTypeArr, GUILayout.Width(100));
                t["layerType"] = layerTypeArr[layerTypeIndex];

                string viewType = t["viewType"];
                int viewTypeIndex = Array.IndexOf(viewTypeArr, viewType);
                if (viewTypeIndex < 0)
                {
                    viewTypeIndex = 0;
                }
                viewTypeIndex = EditorGUILayout.Popup(viewTypeIndex, viewTypeArr, GUILayout.Width(100));
                t["viewType"] = viewTypeArr[viewTypeIndex];

                int hideSceneIndex = t.ContainsKey("hideScene") ? Array.IndexOf(hideSceneArr, t["hideScene"]) : 0;
                if (hideSceneIndex < 0)
                {
                    hideSceneIndex = 0;
                }
                hideSceneIndex = EditorGUILayout.Popup(hideSceneIndex, hideSceneArr, GUILayout.Width(100));
                t["hideScene"] = hideSceneArr[hideSceneIndex];

                int hideAllVisibleIndex = t.ContainsKey("hideAllVisible") ? Array.IndexOf(hideAllVisibleArr, t["hideAllVisible"]) : 0;
                if (hideAllVisibleIndex < 0)
                {
                    hideAllVisibleIndex = 0;
                }
                hideAllVisibleIndex = EditorGUILayout.Popup(hideAllVisibleIndex, hideAllVisibleArr, GUILayout.Width(100));
                t["hideAllVisible"] = hideAllVisibleArr[hideAllVisibleIndex];

                string constantView = t.ContainsKey("constantView") ? t["constantView"] : "FALSE";
                int constantViewIndex = Array.IndexOf(constantTypeArr, constantView);
                if (constantViewIndex < 0)
                {
                    constantViewIndex = 0;
                }
                constantViewIndex = EditorGUILayout.Popup(constantViewIndex, constantTypeArr, GUILayout.Width(100));
                t["constantView"] = constantTypeArr[constantViewIndex];


                string viewPath = t.ContainsKey("viewPath") ? t["viewPath"] : "";
                t["viewPath"] = EditorGUILayout.TextField(viewPath);

                if (GUILayout.Button("删除", GUILayout.Width(100)))
                {
                    taskList.Remove(t);
                }

                EditorGUILayout.EndHorizontal();
                EditorGUILayout.Space();
            }
            EditorGUILayout.EndScrollView();
        }

        //this.Repaint();//实时刷新
    }

    //获取model
    private string GetCodeModelContent(string modelName)
    {
        string filePath = Application.dataPath + string.Format("/{0}/Editor/ViewEditor/ViewModel/", AppConst.AppName) + modelName + ".txt";
        string content = File.ReadAllText(filePath);
		return content;
	}

    //将Dictionary数据转成json保存到本地文件  
    private void SaveJsonToFile()
    {
        string filePath = Application.dataPath + string.Format("/{0}/Editor/ViewEditor/ViewEditor.json", AppConst.AppName);

        //找到当前路径
        FileInfo file = new FileInfo(filePath);
        //判断有没有文件，有则打开文件，，没有创建后打开文件
        StreamWriter sw = file.CreateText();
        //ToJson接口将你的列表类传进去，，并自动转换为string类型
        string json = JsonMapper.ToJson(taskList);
        json = json.Replace("},", "},\n");
        //将转换好的字符串存进文件，
        sw.WriteLine(json);
        //注意释放资源
        sw.Close();
        sw.Dispose();

        //AssetDatabase.Refresh();
    }

    //Json文件读取
    public void LoadJsonFromFile()
    {
        string filePath = Application.dataPath + string.Format("/{0}/Editor/ViewEditor/ViewEditor.json", AppConst.AppName);

        //读取Json文件.
        //当前的json文件是一个数组.所以使用了<List<TestData>>来读取.
        //根据使用的数据类型<T>值可以是任何类型.相应返回值做一些修改即可.非常方便.
        taskList = JsonMapper.ToObject<List<Dictionary<string, string>>>(new JsonReader(File.ReadAllText(filePath)));
        taskList.Sort((a, b) =>
        {
            return a["viewName"].CompareTo(b["viewName"]);
        });
        init = true;
    }

    public static string CreateLuaConfig(List<Dictionary<string, string>> taskList, string view_def_model)
    {
        string text = "";
        for (int i = 0; i < taskList.Count; i++)
        {
            Dictionary<string, string> dictionary = taskList[i];
            text = text + dictionary["viewName"].ToUpper() + "=\"" + dictionary["viewName"].Substring(0, 1).ToUpper() + dictionary["viewName"].Substring(1) + "\",\n";
        }
        text = text.Substring(0, text.Length - 1);
        string str = view_def_model.Replace("{viewDefs}", "{" + text + "}");
        string text2 = "\nVIEW_CONFIG={}\n";
        for (int j = 0; j < taskList.Count; j++)
        {
            Dictionary<string, string> dictionary2 = taskList[j];
            text2 = text2 + "VIEW_CONFIG[VIEW." + dictionary2["viewName"].ToUpper() + "]={";
            if (dictionary2.ContainsKey("layerType") && dictionary2["layerType"] != "NONE")
            {
                text2 = text2 + "layerType=LAYER_TYPE." + dictionary2["layerType"] + ",";
            }
            if (dictionary2.ContainsKey("viewType") && dictionary2["viewType"] != "NONE")
            {
                text2 = text2 + "viewType=VIEW_TYPE." + dictionary2["viewType"] + ",";
            }
            if (dictionary2.ContainsKey("hideScene") && dictionary2["hideScene"] != "NONE")
            {
                text2 = text2 + "hideScene=" + dictionary2["hideScene"] + ",";
            }
            if (dictionary2.ContainsKey("hideAllVisible") && dictionary2["hideAllVisible"] != "NONE")
            {
                text2 = text2 + "hideAllVisible=" + dictionary2["hideAllVisible"] + ",";
            }
            if (dictionary2.ContainsKey("constantView") && dictionary2["constantView"] != "NONE")
            {
                text2 = text2 + "constantView=" + dictionary2["constantView"] + ",";
            }
            if (dictionary2.ContainsKey("viewPath"))
            {
                text2 = text2 + "viewPath=\"" + dictionary2["viewPath"] + "\",";
            }
            text2 = text2.Substring(0, text2.Length - 1);
            text2 += "}\n";
        }
        return str + text2;
    }

}